package cn.yangliu.nacos.oauth2.config;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Service;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020-01-12
 */
@Service
public class RedisAuthenticationCodeServiceImpl
        extends RandomValueAuthorizationCodeServices {
    /** LOGGER. */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(RedisAuthenticationCodeServiceImpl.class);

    /** oauth2RedisTemplate. */
    private RedisTemplate<String, Object> oauth2RedisTemplate = new RedisTemplate<>();

    /** AUTH_CODE_KEY. */
    private static final String AUTH_CODE_KEY = "oauth2_code";

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @PostConstruct
    public void init() {
        oauth2RedisTemplate = new RedisTemplate<>();
        oauth2RedisTemplate.setConnectionFactory(redisConnectionFactory);
        oauth2RedisTemplate.afterPropertiesSet();
    }
    /**
     * Override remove method.
     *
     * @param code the code
     * @return the o auth 2 authentication
     */
    @Override
    protected OAuth2Authentication remove(String code) {
        OAuth2Authentication authentication = null;
        try {
            HashOperations<String, String, OAuth2Authentication> hashOper = oauth2RedisTemplate
                    .opsForHash();
            authentication = hashOper.get(AUTH_CODE_KEY, code);
            if (null != authentication) {
                oauth2RedisTemplate.opsForHash().delete(AUTH_CODE_KEY, code);
            }
        } catch (Exception e) {
            LOGGER.error("Remove code {} failed!", code, e);
        }
        return authentication;
    }

    /**
     * Override store method.
     *
     * @param code the code
     * @param authentication the authentication
     */
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        try {
            HashOperations<String, String, OAuth2Authentication> hashOper = oauth2RedisTemplate
                    .opsForHash();
            hashOper.put(AUTH_CODE_KEY, code, authentication);
        } catch (Exception e) {
            LOGGER.error("Store code {} failed!", code, e);
        }
    }
}
